package com.leyou.item.service;

import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    public List<Category> queryCategorysByPid(Long pid) {
        Category record = new Category();
        record.setParentId(pid);
        List<Category> list = categoryMapper.select(record);
        //判空
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return list;
    }

    public List<Category> queryCategorysByIds(List<Long> ids) {
        List<Category> list = categoryMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return list;
    }


    /**
     *
     * 首页分类导航 查询全部分类
     */
    public List<CategoryDTO> queryCategoryDtoByPid(Long pid) {
        List<Category> categories = queryCategorysByPid(pid);
        List<CategoryDTO> categoryDTOS1 = BeanHelper.copyWithCollection(categories, CategoryDTO.class);
        List<CategoryDTO> categoryDTOS = categoryDTOS1.subList(0, 16);
        List<Category> categoriesChild = categoryMapper.queryCategoryChild();
        List<CategoryDTO> categoriesChildDTOS = BeanHelper.copyWithCollection(categoriesChild, CategoryDTO.class);
        Map<Long, List<CategoryDTO>> map = categoriesChildDTOS.stream().collect(Collectors.groupingBy(CategoryDTO::getParentId));
        categoryDTOS.forEach(CategoryDTO->{
            CategoryDTO.setParams(map.get(CategoryDTO.getId()));
            CategoryDTO.getParams().forEach(param->{
                param.setParams(map.get(param.getId()));
            });
        });
        return categoryDTOS;
    }
}
